/*******************************************************************************
 * $Header$
 * $Revision$
 * $Date$
 *
 *==============================================================================
 *
 * Copyright©hxlife/hulife 
 * All rights reserved.
 * 
 * Created on 2017年9月20日
 *******************************************************************************/

package com.hualife.md.member.service.impl;

import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import com.hualife.md.constants.MDConstants;
import com.hualife.md.member.dao.ex.mapper.AdOrganizationalunitQueryMapper;
import com.hualife.md.member.dao.mybatis.entity.MemberInfo;
import com.hualife.md.member.dao.mybatis.entity.SynAdOrganizationalunit;
import com.hualife.md.member.dao.mybatis.entity.SynAdOrganizationalunitExample;
import com.hualife.md.member.dao.mybatis.entity.SynAdUser;
import com.hualife.md.member.dao.mybatis.entity.SynAdUserExample;
import com.hualife.md.member.dao.mybatis.entity.SynLisLdcom;
import com.hualife.md.member.dao.mybatis.mapper.MemberInfoMapper;
import com.hualife.md.member.dao.mybatis.mapper.SynAdOrganizationalunitMapper;
import com.hualife.md.member.dao.mybatis.mapper.SynAdUserMapper;
import com.hualife.md.member.dao.mybatis.mapper.SynLisLdcomMapper;
import com.hualife.md.member.service.IActiveDirectoryUserTransferService;

/**
 * @description: TODO 此处填写 class 信息
 * @author 孙小冬 (mailto:sunxiaodong001@hualife.cc)
 */
@Service("activeDirectoryUserTransferService")
public class ActiveDirectoryUserTransferServiceImpl implements
		IActiveDirectoryUserTransferService {
	private static final Logger logger = LoggerFactory
			.getLogger(ActiveDirectoryUserTransferServiceImpl.class);

	@Autowired
	private SynAdUserMapper synAdUserMapper;

	@Autowired
	private MemberInfoMapper memberInfoMapper;

	@Autowired
	private SynLisLdcomMapper synLisLdcomMapper;

	@Autowired
	private SynAdOrganizationalunitMapper synAdOrganizationalunitMapper;
	
	@Autowired
	private AdOrganizationalunitQueryMapper adOrganizationalunitQueryMapper;

	@Autowired
	private JdbcTemplate jdbcTemplate;

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.hualife.md.member.service.IActiveDirectoryUserTransferService#transfer
	 * ()
	 */
	@Override
	public void transfer() {
		SynAdUserExample example = new SynAdUserExample();
		SynAdUserExample.Criteria criteria = example.createCriteria();
		criteria.andIssynedtouserEqualTo(MDConstants.NOT_SYNED);
		List<SynAdUser> adUserList = synAdUserMapper.selectByExample(example);
		// 查找冗余数据
		String sql = " TRUNCATE TABLE member_info";
		jdbcTemplate.execute(sql);
		for (SynAdUser adUser : adUserList) {
			try {
				String userId = adUser.getSamaccountname();
				MemberInfo member = memberInfoMapper.selectByPrimaryKey(userId);
				Date now = new Date();
				if (member == null) {
					member = new MemberInfo();
					member.setCreateTime(now);
				}

				member.setMemberId(adUser.getSamaccountname());
				member.setMemberName(adUser.getName());

				String description = adUser.getDescription();
				if (description == null || "".equals(description.trim())) {
					member.setOrganizationCode("");
				} else {
					// description字段赋值举例：“总公司;managecom=86”，需根据“;”进行拆分，然后截取“managecom=”后的数据“86”
					String[] desList = description
							.split(MDConstants.SEPARATOR_SEMICOLON);
					for (String des : desList) {
						if (des.toLowerCase().startsWith(
								MDConstants.PREFIX_MANAGECOM)) {

							String organizationCode = adUser.getDescription()
									.substring(
											MDConstants.PREFIX_MANAGECOM
													.length());
							if (organizationCode != null
									&& !"".equals(organizationCode.trim())) {
								SynLisLdcom ldcom = synLisLdcomMapper
										.selectByPrimaryKey(organizationCode
												.trim());
								if (ldcom != null)
									member.setOrganizationCode(organizationCode
											.trim());
								else
									member.setOrganizationCode("");
							}
						}
					}
				}

				String dnstr = adUser.getDn();
				// 用户DN值样式："CN=卜树婷,OU=江苏电商座席,OU=江苏多元业务部,OU=江苏分公司本部,OU=江苏分公司"
				dnstr = dnstr.substring(dnstr
						.indexOf(MDConstants.SEPARATOR_COMMA) + 1); // 去掉CN部分
				// 获取目录的ID
				SynAdOrganizationalunitExample ouexample = new SynAdOrganizationalunitExample();
				SynAdOrganizationalunitExample.Criteria oucriteria = ouexample
						.createCriteria();
				oucriteria.andDnEqualTo(dnstr);
				List<SynAdOrganizationalunit> synAdOrganizationalunit = synAdOrganizationalunitMapper
						.selectByExample(ouexample);

				if (synAdOrganizationalunit != null
						&& synAdOrganizationalunit.size() > 0)
					member.setOrganizationunitCode(synAdOrganizationalunit.get(
							0).getUsncreated());
				StringBuffer ou = new StringBuffer();
				String[] dnlist = dnstr.split(MDConstants.SEPARATOR_COMMA);
				int i = 0;
				for (String dn : dnlist) {
					if (dn.startsWith(MDConstants.PREFIX_OrganizationUnit)
							&& i < MDConstants.SHORT_UNIT_PART) { // DN中下级机构在前，所以要反向插入
						String value = dn
								.substring(MDConstants.PREFIX_OrganizationUnit
										.length());
						ou.insert(0, value);
						ou.insert(0, MDConstants.SEPARATOR_SLANT);
						i++;
					}
				}
				if (ou.length() > 0) {
					ou.deleteCharAt(0);
					member.setOrganizationUnit(ou.toString());
				}

				member.setDepartment(adUser.getDepartment());
				member.setTitle(adUser.getTitle());
				member.setEmail(adUser.getMail());
				boolean state = ADUserAccountControl
						.checkAccountDisable(Integer.parseInt(adUser
								.getUseraccountcontrol()));
				member.setState(state ? MDConstants.ACCOUNT_DISABLE
						: MDConstants.ACCOUNT_VALID);
				member.setUpdateTime(now);
				if (this.save(member)) {
					adUser.setIssynedtouser(MDConstants.IS_SYNED);
					adUser.setUpdateTime(now);
					synAdUserMapper.updateByPrimaryKeySelective(adUser);
				} else {
					adUser.setIssynedtouser(MDConstants.SYNED_ERROR);
					adUser.setUpdateTime(now);
					synAdUserMapper.updateByPrimaryKeySelective(adUser);
				}
			} catch (Exception e) {
				logger.error("数据异常，原因是：" + e.getMessage());
				continue;
			}
		}
	}

	private boolean save(MemberInfo member) {
		try {
			memberInfoMapper.deleteByPrimaryKey(member.getMemberId());
			memberInfoMapper.insertSelective(member);
		} catch (Exception e) {
			return false;
		}
		return true;
	}

	/* (non-Javadoc)
	 * @see com.hualife.md.member.service.IActiveDirectoryUserTransferService#transferOU()
	 */
	@Override
	public void transferOU() {
		logger.info("对来自域控系统中的组织架构数据补充上级关系处理开始！");
		SynAdOrganizationalunitExample example = new SynAdOrganizationalunitExample();
		SynAdOrganizationalunitExample.Criteria criteria = example
				.createCriteria();
		criteria.andIssynedtoouEqualTo(MDConstants.NOT_SYNED);

		List<SynAdOrganizationalunit> adOuList = synAdOrganizationalunitMapper
				.selectByExample(example);
		for (SynAdOrganizationalunit adOu : adOuList) {
			try {

				String dnstr = adOu.getDn();
				
				SynAdOrganizationalunit synAdOrganizationalunit = new SynAdOrganizationalunit();
				synAdOrganizationalunit.setUsncreated(adOu.getUsncreated());
				if (dnstr.length() > 0) {
					String pdn = dnstr;
					if (dnstr.indexOf(MDConstants.SEPARATOR_COMMA) > 0)
						pdn = pdn.substring(dnstr.indexOf(MDConstants.SEPARATOR_COMMA) + 1);
					else
						pdn = "";
					String pid = adOrganizationalunitQueryMapper
							.queryPidByDN(pdn);
					synAdOrganizationalunit.setPid(pid);
					synAdOrganizationalunit.setUpdateTime(new Date());
				} else {
					synAdOrganizationalunit.setPid("");
					synAdOrganizationalunit.setUpdateTime(new Date());
				}

				synAdOrganizationalunitMapper
						.updateByPrimaryKeySelective(synAdOrganizationalunit);
			} catch (Exception e) {
				logger.error("数据异常，原因是：" + e.getMessage());
				continue;
			}
		}

		logger.info("对来自域控系统中的组织架构数据补充上级关系处理完毕！");
	}

}

/*
 * 修改历史 $Log$
 */